package com.imut.lagain.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.Message;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 消息数据访问层
 */
@Mapper
public interface MessageRepository extends BaseMapper<Message> {
    
    /**
     * 获取两个用户之间的聊天记录（分页）
     */
    @Select("SELECT * FROM message WHERE " +
            "((sender_id = #{userId1} AND receiver_id = #{userId2}) OR " +
            "(sender_id = #{userId2} AND receiver_id = #{userId1})) " +
            "AND is_deleted = 0 " +
            "ORDER BY create_time DESC")
    IPage<Message> findChatHistory(Page<Message> page, 
                                  @Param("userId1") Long userId1, 
                                  @Param("userId2") Long userId2);
    
    /**
     * 获取用户的所有聊天对话列表
     */
    @Select("SELECT DISTINCT " +
            "CASE WHEN sender_id = #{userId} THEN receiver_id ELSE sender_id END as partner_id, " +
            "MAX(create_time) as last_message_time " +
            "FROM message " +
            "WHERE (sender_id = #{userId} OR receiver_id = #{userId}) " +
            "AND is_deleted = 0 " +
            "GROUP BY partner_id " +
            "ORDER BY last_message_time DESC")
    List<Object> findChatPartners(@Param("userId") Long userId);
    
    /**
     * 获取两个用户之间的最新消息
     */
    @Select("SELECT * FROM message WHERE " +
            "((sender_id = #{userId1} AND receiver_id = #{userId2}) OR " +
            "(sender_id = #{userId2} AND receiver_id = #{userId1})) " +
            "AND is_deleted = 0 " +
            "ORDER BY create_time DESC LIMIT 1")
    Message findLatestMessage(@Param("userId1") Long userId1, @Param("userId2") Long userId2);
    
    /**
     * 获取用户未读消息数量
     */
    @Select("SELECT COUNT(*) FROM message WHERE " +
            "receiver_id = #{userId} AND is_read = 0 AND is_deleted = 0")
    Long countUnreadMessages(@Param("userId") Long userId);
    
    /**
     * 获取两个用户之间的未读消息数量
     */
    @Select("SELECT COUNT(*) FROM message WHERE " +
            "sender_id = #{senderId} AND receiver_id = #{receiverId} " +
            "AND is_read = 0 AND is_deleted = 0")
    Long countUnreadMessagesBetween(@Param("senderId") Long senderId, 
                                   @Param("receiverId") Long receiverId);
    
    /**
     * 标记消息为已读
     */
    @Update("UPDATE message SET is_read = 1, read_time = #{readTime} " +
            "WHERE id = #{messageId} AND is_deleted = 0")
    int markAsRead(@Param("messageId") Long messageId, @Param("readTime") LocalDateTime readTime);
    
    /**
     * 批量标记消息为已读
     */
    @Update("UPDATE message SET is_read = 1, read_time = #{readTime} " +
            "WHERE sender_id = #{senderId} AND receiver_id = #{receiverId} " +
            "AND is_read = 0 AND is_deleted = 0")
    int markAllAsReadBetween(@Param("senderId") Long senderId, 
                            @Param("receiverId") Long receiverId, 
                            @Param("readTime") LocalDateTime readTime);
    
    /**
     * 获取指定时间范围内的消息
     */
    @Select("SELECT * FROM message WHERE " +
            "((sender_id = #{userId1} AND receiver_id = #{userId2}) OR " +
            "(sender_id = #{userId2} AND receiver_id = #{userId1})) " +
            "AND create_time BETWEEN #{startTime} AND #{endTime} " +
            "AND is_deleted = 0 " +
            "ORDER BY create_time ASC")
    List<Message> findMessagesByTimeRange(@Param("userId1") Long userId1, 
                                         @Param("userId2") Long userId2,
                                         @Param("startTime") LocalDateTime startTime,
                                         @Param("endTime") LocalDateTime endTime);
    
    /**
     * 搜索消息内容
     */
    @Select("SELECT * FROM message WHERE " +
            "((sender_id = #{userId1} AND receiver_id = #{userId2}) OR " +
            "(sender_id = #{userId2} AND receiver_id = #{userId1})) " +
            "AND content LIKE CONCAT('%', #{keyword}, '%') " +
            "AND is_deleted = 0 " +
            "ORDER BY create_time DESC")
    List<Message> searchMessages(@Param("userId1") Long userId1, 
                                @Param("userId2") Long userId2,
                                @Param("keyword") String keyword);
    
    /**
     * 获取系统消息
     */
    @Select("SELECT * FROM message WHERE " +
            "receiver_id = #{userId} AND message_type = 'SYSTEM' " +
            "AND is_deleted = 0 " +
            "ORDER BY create_time DESC")
    IPage<Message> findSystemMessages(Page<Message> page, @Param("userId") Long userId);
    
    /**
     * 删除过期消息（软删除）
     */
    @Update("UPDATE message SET is_deleted = 1 " +
            "WHERE create_time < #{expireTime}")
    int deleteExpiredMessages(@Param("expireTime") LocalDateTime expireTime);
}